package com.kenobi.visualData;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.kenobi.visualData.VisualDataModel.VisualData;

public class VisualDataDBHandler {
	
	private DBHelper _dbHelper;
	private SQLiteDatabase _database;
	

	private VisualDataDBHandler(Context context){
		_dbHelper = new DBHelper(context);
		_database = _dbHelper.getWritableDatabase();
	}
	
	
	public static VisualDataDBHandler open(Context context) throws SQLException {
		VisualDataDBHandler handler = new VisualDataDBHandler(context);
		return handler;
	}

	
	public void close(){
		_dbHelper.close();
	}
	
	
	public long insert(VisualData visualData, int musicID){

		ContentValues values = new ContentValues();
		values.put("musicID", musicID);
		values.put("title", visualData.title);
		values.put("imgURL", visualData.imgURL);
		values.put("articleLink", visualData.articleLink);
		values.put("filePath", visualData.filePath);
		return _database.insert("visualData", null, values);
	}
	
	public int remove(int musicID) {
		int removeNum = _database.delete("visualData", " musicID = ? ", new String[]{Integer.toString(musicID)});
		return removeNum;
	}
	
	public void insertList(ArrayList<VisualData> arrListVisualData, int musicID){
		SQLiteStatement stmt = _database.compileStatement("INSERT INTO visualData VALUES(?, ?,?,?,?,?)");
		for(VisualData visualData : arrListVisualData){
			stmt.clearBindings();
			stmt.bindLong(2, musicID);
			stmt.bindString(3, visualData.title);
			stmt.bindString(4, visualData.imgURL);
			
			if(visualData.articleLink == null){
				stmt.bindString(5, "");
			}
			else{
				stmt.bindString(5, visualData.articleLink);
			}
			
			if(visualData.filePath == null){
				stmt.bindString(6, "");
			}else{
				stmt.bindString(6, visualData.filePath);
			}
			
			stmt.executeInsert();
		}		
	}

	
	public Cursor select(int musicID) throws SQLException {
		Cursor cursor = _database.query(true, "visualData"
				, new String[]{ "visualDataID", "title", "imgURL", "articleLink", "filePath" }
				, "musicID" + "=" + musicID, null, null, null, null, null);
		
		if(cursor != null){
			cursor.moveToFirst();
		}
		return cursor;
	}
	
	
	public int updateFilePath(int visualDataID, String filePath){
		ContentValues values = new ContentValues();
		values.put("filePath", filePath);
		return _database.update("visualData", values, "visualDataID = ?", new String[]{Integer.toString(visualDataID)});
	}
	
}
